import request from "request";
import { createPromise } from "../utils/util";

// 科大讯飞星火大模型接口
export interface ISparkAiMessage {
    role: 'user' | 'assistant' | 'system';
    content: string;
}
export const sparkAiApi = (messages: ISparkAiMessage[]) => {
    console.log('开始请求');
    const {promise, resolve, reject} = createPromise();
    const options = {
        url: 'https://spark-api-open.xf-yun.com/v1/chat/completions', // 请求的URL
        method: 'post', // 请求方法
        headers: {
            'User-Agent': 'life_us_app',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ujgElmfuHRXHpsyCFxIO:NIsFsbLAgMraPldgtGjs', // 这里填写你的accessToken
        },
        json: {
            "model":"generalv3.5",
            "messages": messages,
            "stream": false
        }
    };
    request(options, function (err, res, body) {
        if (err) {
            console.log(err);
            reject(err);
        } else {
            console.log('返回结果:', body);
            // const datas: string[] = body.split('\n');
            // datas.forEach(data => {
            //     if (data !== '[DONE]' && data !== '') {
            //         const result = data.split(' ')[1];
            //         console.log('返回结果：', result);
            //     }
            // });
            const { code, choices } = body;
            if (code === 0) {
                console.log('返回结果：', choices[0]);
                const { role, content } = choices[0];
                if (role === 'assistant') {
                    resolve(content);
                }
            }
        }
    });

    return promise;
};